package com.wechar.pub_account.util;

import org.apache.http.message.BasicNameValuePair;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class HttpUtil {

    public static final String POST = "POST";
    public static final String GET = "GET";

    public static String openUrl(String url, String outString, String method) throws Exception{
        URL uri = new URL(url);
        HttpURLConnection connection = (HttpURLConnection)uri.openConnection();
        connection.setRequestMethod(method);
        if("POST".equals(method)) {
            connection.setDoOutput(true);
            connection.connect();
            OutputStream out = connection.getOutputStream();
            out.write(outString.getBytes(StandardCharsets.UTF_8));
        }
        if (connection.getResponseCode() == 200) {
            InputStream inputStream = connection.getInputStream();
            // 封装输入流is，并指定字符集
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            // 存放数据
            StringBuilder stringBuilder = new StringBuilder();
            String temp = null;
            while ((temp = bufferedReader.readLine()) != null) {
                stringBuilder.append(temp);
            }
            return stringBuilder.toString();
        }
        return "";
    }

    public static String openUrl(String url, String method) throws Exception{
        URL uri = new URL(url);
        HttpURLConnection connection = (HttpURLConnection)uri.openConnection();
        connection.setRequestMethod(method);
        if("POST".equals(method)) {
            connection.connect();
        }
        if (connection.getResponseCode() == 200) {
            InputStream inputStream = connection.getInputStream();
            // 封装输入流is，并指定字符集
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            // 存放数据
            StringBuilder stringBuilder = new StringBuilder();
            String temp = null;
            while ((temp = bufferedReader.readLine()) != null) {
                stringBuilder.append(temp);
            }
            return stringBuilder.toString();
        }
        return "";
    }

}
